const app = getApp();
const config = app.globalData.config;
const util = app.globalData.util;
const share = require('../../template/share/share.js')
// pages/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activityId: 0,
    result: {},
    isShowJoin: true,
    isShowLength: false,
    isShowAddress: false,
    endTimeList: [],
    countDownList: [],
    userInfo: null,
    pushUser: null,
    scrollTop: 0,
    tab: 0,
    joinUser: [],
    joinCount: 0,
    luckyUser: [],
    isLucky: false,
    name: '',
    phone: '',
    address: '',
    share: {
      isShow: false,
      index: 1,
      param: '{}'
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var {
      activityId,
      scene
    } = options;
    //赠送幸运值
    if (!!scene) {
      scene = decodeURIComponent(scene)
      var aid = scene.split('&')[0];
      var uid = scene.split('&')[1];
      activityId = aid;
      wx.request({
        url: config.addPointsUrl,
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          userId: uid,
          pointsRule: 'INVITE'
        },
        success: function(resp) {},
        fail(res) {}
      })
    }
    if (!activityId) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
      return;
    }
    var userInfo = wx.getStorageSync('sUserInfo');
    this.setData({
      activityId: activityId,
      userInfo: userInfo
    })
    this.getActivity();
    this.getActivityUser();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.getActivity();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  getActivity() {
    var that = this;
    var userInfo = that.data.userInfo;
    var userId = !!userInfo ? userInfo.id : null;
    wx.request({
      url: config.activityUrl,
      method: "GET",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        id: that.data.activityId,
        userId: userId
      },
      success: function(resp) {
        if (resp.data.result == 1) {
          var temp_dt = resp.data.data.activity.openTime;
          //分享参数
          var param = {
            userId: that.data.userInfo.id,
            activityId: that.data.activityId,
            path: 'pages/detail/detail',
            coverPhoto: resp.data.data.activity.coverPage,
            title: resp.data.data.activity.title,
            openTime: util.formatDate(temp_dt, 1)
          }
          that.setData({
            result: resp.data.data,
            isShowLength: resp.data.data.details.length > 1,
            endTimeList: [temp_dt],
            share: {
              isShow: false,
              index: 1,
              param: JSON.stringify(param)
            }
          })
          if (resp.data.data.isJoin) {
            that.setData({
              isShowJoin: false
            })
          }
          // 执行倒计时函数
          that.countDown();
          // 获得发起人信息
          that.getPushUser(resp.data.data.activity.userId);
          if (resp.data.data.activity.isOpen == '1') {
            that.getIsLucky(userId);
            that.getLuckyUser();
          }
        }
      },
      fail(res) {},
      complete(res) {
        wx.stopPullDownRefresh();
      }
    })
  },
  onJoin: function(e) {
    var that = this;
    var userInfo = that.data.userInfo;
    if (!userInfo) {
      wx.navigateTo({
        url: '/pages/me/me',
      })
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    }
    wx.showLoading({
      title: '参与中',
      mask: true
    })
    var model = {
      userId: userInfo.id,
      activityId: that.data.activityId,
      formId: e.detail.formId
    };
    wx.request({
      url: config.joinUrl,
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: model,
      success: function(resp) {
        if (resp.data.result == 1) {
          that.setData({
            isShowJoin: false
          })
          that.getActivityUser();
        } else {
          wx.showToast({
            title: resp.data.msg,
            icon: 'none'
          })
        }
      },
      fail(res) {},
      complete(res) {
        wx.hideLoading();
      }
    })
  },
  /**
   * 倒计时函数
   */
  countDown() {
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.endTimeList;
    let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let endTime = new Date(o).getTime();
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: util.formatNumber(day),
          hou: util.formatNumber(hou),
          min: util.formatNumber(min),
          sec: util.formatNumber(sec)
        }
      } else { //活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
      }
      countDownArr.push(obj);
    })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      countDownList: countDownArr
    })
    setTimeout(this.countDown, 1000);
  },
  /**
   * 获取发起人信息
   */
  getPushUser(userId) {
    var that = this;
    wx.request({
      url: config.getUserUrl + userId,
      method: "GET",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(resp) {
        that.setData({
          pushUser: resp.data.data
        })
      }
    })
  },
  /**
   * 参加用户
   */
  getActivityUser() {
    var that = this;
    wx.request({
      url: config.activityUserUrl,
      method: "GET",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        id: that.data.activityId,
        pageIndex: 1,
        pageSize: 8
      },
      success: function(resp) {
        that.setData({
          joinUser: resp.data.data.users,
          joinCount: resp.data.data.count
        })
      }
    })
  },
  /**
   * 是否中奖
   */
  getIsLucky(userId) {
    var that = this;
    if (!userId) {
      return;
    }
    wx.request({
      url: config.isLuckyUrl,
      method: "GET",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        userId: userId,
        activityId: that.data.activityId
      },
      success: function(resp) {
        that.setData({
          isLucky: resp.data.data
        })
      }
    })
  },
  /**
   * 中奖者名单
   */
  getLuckyUser() {
    var that = this;
    wx.request({
      url: config.luckyUserUrl,
      method: "GET",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        id: that.data.activityId,
        pageIndex: 1,
        pageSize: 8
      },
      success: function(resp) {
        that.setData({
          luckyUser: resp.data.data.reList
        })
      }
    })
  },
  /**
   * 切换tab
   */
  onChangeDP(e) {
    this.setData({
      tab: e.detail.index
    })
  },
  //添加幸运值
  onPoints() {
    var that = this;
    var userInfo = that.data.userInfo;
    if (!userInfo) {
      wx.navigateTo({
        url: '/pages/me/me',
      })
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    }
    var model = {
      userId: that.data.userInfo.id,
      pointsRule: 'NOPRIZE'
    };
    wx.request({
      url: config.addPointsUrl,
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: model,
      success: function(resp) {
        if (resp.data.result == 1) {
          wx.showToast({
            title: '领取成功',
            icon: 'none'
          })
        } else if (resp.data.result == 2) {
          wx.showToast({
            title: '今日已领取',
            icon: 'none'
          })
        }
      }
    })
  },
  onShowAddress() {
    this.setData({
      isShowAddress: true
    })
  },
  onCloseAddress() {
    this.setData({
      isShowAddress: false
    })
  },
  onWxAddress() {
    var that = this;
    wx.chooseAddress({
      success(res) {
        console.log(res)
        that.setData({
          name: res.userName,
          phone: res.telNumber,
          address: res.provinceName + res.cityName + res.countyName + res.detailInfo
        })
      }
    });
  },
  onName(e) {
    this.setData({
      name: e.detail
    })
  },
  onPhone(e) {
    this.setData({
      phone: e.detail
    })
  },
  onAddress(e) {
    this.setData({
      address: e.detail
    })
  },
  //设置地址
  onSureAddress() {
    var that = this;
    if (!that.data.name) {
      wx.showToast({
        title: '收货人名称必填',
        icon: 'none'
      })
      return;
    } else if (!that.data.phone) {
      wx.showToast({
        title: '收货人电话必填',
        icon: 'none'
      })
      return;
    } else if (!that.data.address) {
      wx.showToast({
        title: '收货人地址必填',
        icon: 'none'
      })
      return;
    }
    var model = {
      userId: that.data.userInfo.id,
      activityId: that.data.activityId,
      address: that.data.name + ',' + that.data.phone + ',' + that.data.address
    };
    wx.request({
      url: config.setAddressUrl,
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: model,
      success: function(resp) {
        wx.showToast({
          title: resp.data.msg,
          icon: 'none'
        })
        that.onCloseAddress();
      }
    })
  },
  //分享相关
  onCloseShare: share.onCloseShare,
  onShowShare: share.onShowShare,
  onSelectShare: share.onSelectShare
})